package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-data-hub/cache"
	"novel-data-hub/models"
	"strconv"
	"time"
)

func CommercePerList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	/*
		SELECT
		  commerce_pers.id as Pid,
		  commerce_roles.role_code as RoleCode,
		  commerce_roles.role_name as RoleName,
		  commerce_roles.role_create as RoleCreate,
		  commerce_pers.per_type as PerType,
		  commerce_pers.per_name as PerName
		FROM
		  commerce_roles
		  LEFT JOIN commerce_pers ON commerce_pers.rid = commerce_roles.id
		WHERE
		  commerce_pers.id = 1
	*/
	var list []models.CommercePerList
	redis_key := "commerce_per_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("commerce_roles").
			Select("commerce_pers.id as Pid",
				"commerce_roles.role_code as RoleCode",
				"commerce_roles.role_name as RoleName",
				"commerce_roles.role_create as RoleCreate",
				"commerce_pers.per_type as PerType",
				"commerce_pers.per_name as PerName",
			).
			Joins("LEFT JOIN commerce_pers ON commerce_pers.rid = commerce_roles.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var count int64
	models.DB.Model(&models.CommercePer{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  list,
		"count": count,
	})
	return
}

func CommercePerDetail(c *gin.Context) {
	id := c.Query("id")

	var list models.CommercePerList
	redis_key := "commerce_per_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("commerce_roles").
			Select("commerce_pers.id as Pid",
				"commerce_roles.role_code as RoleCode",
				"commerce_roles.role_name as RoleName",
				"commerce_roles.role_create as RoleCreate",
				"commerce_pers.per_type as PerType",
				"commerce_pers.per_name as PerName",
			).
			Joins("LEFT JOIN commerce_pers ON commerce_pers.rid = commerce_roles.id").
			Where("commerce_pers.id = ?", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": list,
	})
	return
}
